package advanced_select;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import advanced_select.Employee;
import advanced_select.EmployeeMapper;

public class Test1 {

	@Test
	public void testUnionQuery1() throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

		SqlSession session = sqlSessionFactory.openSession();
		try {
			EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
			Employee employee = mapper.getEmployeeAndDepartment(1);
			System.out.println(employee);
			System.out.println(employee.getDepartment());
		} finally {
			session.close();
		}
	}
	
	@Test
	public void testStepQueryAndLazyLoading() throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

		SqlSession session = sqlSessionFactory.openSession();
		try {
			EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
			Employee employee = mapper.getEmployeeByIdStep(1);
			System.out.println(employee.getLastName());
			System.out.println(employee.getDepartment());
		} finally {
			session.close();
		}
	}
	
	@Test
	public void getDepartmentAndInnerEmployeeById() throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

		SqlSession session = sqlSessionFactory.openSession();
		try {
			DepartmentMapper departmentMapper = session.getMapper(DepartmentMapper.class);
			Department department = departmentMapper.getDepartmentAndInnerEmployeeById(1);
			System.out.println(department);
			System.out.println(department.getEmployees());
		} finally {
			session.close();
		}
	}
	
	@Test
	public void getDepartmentStep() throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

		SqlSession session = sqlSessionFactory.openSession();
		try {
			DepartmentMapper departmentMapper = session.getMapper(DepartmentMapper.class);
			Department department = departmentMapper.getDepartmentStep(1);
			System.out.println(department.getDepartmentName());
			System.out.println(department.getEmployees());
		} finally {
			session.close();
		}
	}
}
